<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
      label-width="68px">
      <!-- <el-form-item label="协议标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入协议标题"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>-->
      <el-form-item label="客户端" prop="classify">
        <el-select v-model="queryParams.clientType" placeholder="客户端类型" clearable>
          <el-option v-for="dict in dict.type.client_client_type" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="classify">
        <el-select v-model="queryParams.enabled" placeholder="启用状态" clearable>
          <el-option label="启用" value="true" />
          <el-option label="禁用" value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="title">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mall:banner:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate" v-hasPermi="['mall:banner:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDeleteAll" v-hasPermi="['mall:banner:remove']">批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="rotationChartList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="展示顺序" align="center" prop="orderNum" width="80" />
      <el-table-column label="客户端类型" prop="clientType" align="center" width="100" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.client_client_type" :value="scope.row.clientType" />
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" align="center" width="120" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="背景色" align="center" prop="backgroundColor" width="100">
        <template slot-scope="scope">
          <el-color-picker v-model="scope.row.backgroundColor" disabled></el-color-picker>
        </template>
      </el-table-column>
      <el-table-column label="缩略图片" align="center" width="100">
        <template slot-scope="scope">
          <el-image :src="scope.row.image" @click="clickOriginal(scope.row)"
          :preview-src-list="scope.row.originals"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="启用开关" align="center" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enabled" :active-value="true" :inactive-value="false"
            @change="handleEnabledStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="170" :show-overflow-tooltip="true"/>
      <el-table-column label="结束时间" align="center" prop="endTime" width="170" :show-overflow-tooltip="true"/>
      <el-table-column label="跳转地址" align="center" prop="path" width="400" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateTime(scope.row)"
            v-hasPermi="['mall:banner:time:edit']">修改时间</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openUpdateImageView(scope.row)"
            v-hasPermi="['mall:banner:image:edit']">更改图片</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-share" @click="handleDetal(scope.row)"
            v-hasPermi="['system:notice:remove']">详情</el-button>-->
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['mall:banner:remove']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDataScope" icon="el-icon-delete"
                v-hasPermi="['mall:banner:remove']">删除轮播图</el-dropdown-item>
              <!--
              <el-dropdown-item command="updateDataScope" icon="el-icon-edit"
                v-hasPermi="['mall:banner:edit']">修改轮播图</el-dropdown-item>
              -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改轮播对话框 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户端类型" prop="clientType">
          <el-select v-model="form.clientType" placeholder="客户端类型" clearable>
            <el-option v-for="dict in dict.type.client_client_type" :key="dict.value"
              :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="图片" prop="image" label-width="100px">
          <el-upload action="#" list-type="picture-card" :auto-upload="false"
            :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :on-change="changeImg">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete">
                  <i class="el-icon-download"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete"
                  @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime" class="start">
          <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss" :show-overflow-tooltip="true" ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime" class="start">
          <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss" :show-overflow-tooltip="true" ></el-date-picker>
        </el-form-item>
        <el-form-item label="是否外链">
          <el-radio-group v-model="form.internalLink">
            <el-radio v-for="dict in dict.type.is_internal_link" :key="dict.value" :label="dict.value">{{
                            dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="跳转地址" prop="path">
          <el-input v-model="form.path" type="textarea" placeholder="请输入跳转地址" />
        </el-form-item>
        <el-form-item label="跳转参数" prop="param">
          <el-input v-model="form.param" type="textarea" placeholder="请输入跳转参数" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="背景色" prop="orderNum">
          <el-color-picker v-model="form.backgroundColor"></el-color-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改轮播时间对话框 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :title="title" :visible.sync="openUpdateTimeView" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="开始时间" prop="startTime" class="start">
          <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss" :show-overflow-tooltip="true" ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime" class="start">
          <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss" :show-overflow-tooltip="true" ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormToUpdateTime">确 定</el-button>
        <el-button @click="openUpdateTimeView = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 更改图片对话框 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :title="title" :visible.sync="openChangeImageView" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="图片地址" prop="image">
          <el-upload action="#" list-type="picture-card" :auto-upload="false"
            :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :on-change="changeImg">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete">
                  <i class="el-icon-download"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete"
                  @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
        <el-form-item label="展示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeImage">确 定</el-button>
        <el-button @click="openChangeImageView = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addBanner,
  listBanner,

  getAotationChart,
  delAotationChart,
  updateAotationChart,
  handleEnabledChange,
  handleTimeChange,
  handleImageChange
} from "@/api/mall/banner";
import axios from "axios";
import { getToken } from "@/utils/auth";

export default {
  name: "homeIndex",
  dicts: ["client_client_type", "is_internal_link", "client_page_sign"],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 2,
      // 轮播数据
      rotationChartList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        clientType: undefined,
        createBy: undefined,
        pageSign: 'HOME',
        salaId: '0',
      },
      // 表单参数
      form: {
        isFrame: true,
        pageSign: 'HOME',
        salaId: '0',
        clientType: undefined,
        backgroundColor: '#000'
      },
      // 轮播图
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      imageFileList: [],
      headers: {
        Authorization: "Bearer " + getToken(),
        "Content-Type": "multipart/form-data"
      },
      // 表单校验
      rules: {
        clientType: [
          { required: true, message: "客户端类型不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "change" }
        ],
        image: [
          { required: true, message: "背景图不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              console.log(this.form.image)
              if (!this.form.image) {
                callback(new Error('背景图不能为空'))
              } else {
                callback()
              }
            }, trigger: "blur"
          }
        ]
      },
      openUpdateTimeView: false,
      openChangeImageView: false,
    };
  },
  created () {
    this.getList();
  },
  methods: {
    /** 获取轮播图列表 */
    getList () {
      this.loading = true;
      listBanner(this.queryParams).then(response => {
        this.rotationChartList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.imageFileList = []
      this.form = {
        image: undefined,
        clientType: this.queryParams.clientType,
        isFrame: true,
        path: undefined,
        orderNum: undefined,
        backgroundColor: '#000',
        status: '0',
        isFrame: 'true',
        pageSign: 'HOME',
        salaId: '0',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加轮播图";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.form = JSON.parse(JSON.stringify(row));
      this.form.isFrame = this.form.isFrame.toString()
      this.imageFileList = [{ url: row.image }]
      this.open = true;
      this.title = "修改轮播图";
    },
    /** 提交按钮 */
    submitForm () {
      const loading = this.$loading({
        lock: true,
        text: "上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let formData = new FormData();
      formData.append("file", this.imageFileList[0].raw);
      axios.post(`${process.env.VUE_APP_BASE_API}/oss/common/upload`, formData, {
          headers: this.headers
        }).then(res => {
          if (res.status == 200) {
            let data = res.data;
            if (data.code == 200) {
              this.$modal.msgSuccess("上传成功");
              this.form.image = data.data.url;
              this.form.imageId = data.data.id;
              this.form.startTime = this.parseTime(this.form.startTime, "{y}-{m}-{d} {h}:{i}:{s}")
              this.form.endTime = this.parseTime(this.form.endTime, "{y}-{m}-{d} {h}:{i}:{s}")

              if (this.form.id != undefined) {
                updateBanner(this.form).then(response => {
                  console.log(this.response);
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addBanner(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            } else {
              this.$message.error("上传文件失败" + res.data.msg);
            }
          }
        }).finally(res => {
          loading.close();
        });
    },
    /** 单个删除按钮操作 */
    handleDelete (row) {
      const id = row.id;
      this.$modal
        .confirm("确认删除轮播图吗？")
        .then(function () {
          return delAotationChart(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    // 批量删除
    handleDeleteAll () {
      var ids = this.ids;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delAotationChartAll(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    // 启用状态修改
    handleEnabledStatusChange (row) {
      let text = row.enabled === true ? "启用" : "禁用";
      this.$modal.confirm('确认"' + text + '"此轮播图吗？')
        .then(function () {
          return handleEnabledChange(
            row.id,
            row.enabled
          );
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.enabled = row.enabled === true ? false : true
        });
    },
    // 点击图片
    clickOriginal (row) {
      this.$set(row, 'originals', [row.image])
    },
    // 更多操作触发
    handleCommand (command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDelete(row);
          break;
        case "updateDataScope":
          this.handleUpdate(row);
          break;
        default:
          break;
      }
    },
    //打开需要轮播图时间窗口
    handleUpdateTime(row){
      this.openUpdateTimeView = true;
      this.title = "修改轮播图时间";
      this.form = { ...row };
    },
    //提交修改轮播图时间
    submitFormToUpdateTime(){
      const _this = this;
      this.$modal.confirm("确认修改轮播图时间吗？")
      .then(function () {
        return handleTimeChange(_this.form.id, _this.form.startTime, _this.form.endTime).then(res=>{
          _this.$modal.msgSuccess("修改成功");
          _this.getList();
          _this.openUpdateTimeView = false;
        });
      }).catch(() => {

      });
    },
    openUpdateImageView(row){
      this.imageFileList = [];
      this.title = "更换图片";
      this.openChangeImageView = true;
      this.form = { ...row };
    },
    //更换图片
    changeImage(){
      if(!this.form.orderNum){
        this.$modal.msgError("请填写排序编号");
        return;
      }

      if (!this.imageFileList) {
        this.$modal.msgError("请选择图片");
        return;
      }

      const _this = this;
      this.$modal.confirm("确认更换轮播图图片吗？").then(function () {
        const loading = _this.$loading({
          lock: true,
          text: "上传中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        let formData = new FormData();
        formData.append("file", _this.imageFileList[0].raw);
        axios.post(`${process.env.VUE_APP_BASE_API}/oss/common/upload`, formData, {
          headers: _this.headers
        }).then(res => {
          if (res.status == 200) {
            let data = res.data;
            if (data.code == 200) {
              const changeImageData = {
                imageId: data.data.id,
                image: data.data.url,
                countdown: _this.form.countdown,
                orderNum: _this.form.orderNum
              }
              handleImageChange(_this.form.id, changeImageData).then(res=>{
                _this.$modal.msgSuccess("更换成功");
                _this.getList();
                _this.openChangeImageView = false;
              });
            } else {
              _this.$message.error("上传文件失败" + res.data.msg);
            }
          }
        }).finally(res => {
          loading.close();
        });
      }).catch(function(err) {
        console.log(err)
        _this.$modal.msgError("更换图片出错");
      });
    },
    // 删除图片
    handleRemove (file, fileList) {
      const ul = document.querySelector(".el-upload-list--picture-card");
      ul.removeChild(ul.children[0]);
      ul.nextSibling.style.display = "block";
      console.log(file, fileList);
    },
    // 预览图片
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.raw.url;
      this.dialogVisible = true;
    },
    // 上传图片
    changeImg (file, fileList) {
      const ul = document.querySelector(".el-upload-list--picture-card");
      ul.nextSibling.style.display = "none";
      console.log(file, fileList);
      this.imageFileList = fileList;
    },
  }
};
</script>
<style scoped lang="scss">
::v-deep .imgMax .el-upload--picture-card {
  display: none;
}
::v-deep .el-color-picker__mask {
  display: none;
}
</style>
